package com.kky.pp.activity.me

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.view.isVisible
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.custom.base.config.BaseConfig
import com.custom.base.entity.OkHttpBodyEntity
import com.custom.base.http.OkHttpFromBoy
import com.custom.base.http.OkHttpManager
import com.custom.base.http.SDOkHttpResoutCallBack
import com.custom.base.mvp.BasePresenterImpl
import com.custom.base.util.IntentUtil
import com.custom.base.util.Md5Util
import com.kky.pp.common.Constant
import com.kky.pp.R
import com.kky.pp.entity.BuyResultEnum
import com.kky.pp.common.MemberBuy
import com.kky.pp.common.MemberUnitaryBuy
import com.kky.pp.entity.MemberSubscribeEntity
import com.kky.pp.entity.PrivateAlbumAddEntity
import com.kky.pp.entity.PrivateAlbumEntity
import com.kky.pp.entity.QueryBenefitsEntity
import com.kky.pp.entity.UserProfileEntity
import com.kky.pp.activity.member.BuyPrivateAlbumActivity
import com.kky.pp.activity.member.album.PrivateAlbumActivity
import com.kky.pp.activity.member.album.PrivateAlbumViewActivity
import com.kky.pp.util.CollectionUtils
import com.kky.pp.util.GlideUtil
import com.kky.pp.util.UploadPhoto
import com.kky.pp.view.Loading.LoadingDialog
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.entity.LocalMedia
import io.rong.imkit.IMCenter
import io.rong.imkit.RongIM
import io.rong.imkit.SpName
import io.rong.imkit.event.FirebaseEventTag
import io.rong.imkit.utils.FirebaseEventUtils
import io.rong.imkit.utils.KitStorageUtils
import io.rong.imkit.utils.videocompressor.VideoCompress
import io.rong.imlib.model.UserInfo
import java.io.File


/**
 * 作者：
 * 时间：
 * 描述：我的
 */
class MePresenter : BasePresenterImpl<MeContract.View>(), MeContract.Presenter {
    /**
     * 私密相册CODE
     */
    val PRIVATE_ALBUM_RESULT_CODE = 201
    fun getData() {
        mView?.apply {
            OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                override fun addBody(requestBody: OkHttpBodyEntity) {
                    requestBody.setPost(Constant.user_info_url)
                }
            }, object : SDOkHttpResoutCallBack<UserProfileEntity>(false) {
                override fun onSuccess(entity: UserProfileEntity) {
                    RongIM.getInstance().refreshUserInfoCache(
                        UserInfo(
                            entity.data.userCode,
                            entity.data.nickName,
                            Uri.parse(entity.data.avatarUrl)
                        )
                    )
                    val visibie = if (entity.data.isMember) View.VISIBLE else View.INVISIBLE
                    imgViewMeFragVipFlag.visibility = visibie
                    imgViewMeFragHeadBorder.visibility = visibie

                    val ppvVisibility = BaseConfig.getInstance.getBoolean(
                            SpName.privatePhotoShowUnableFlag,
                            false
                        )
                    conMeFragSecretAlbum.isVisible=!ppvVisibility
                    conMeFragSecretVideo.isVisible = !ppvVisibility
                    conMeFragSecretPic.isVisible = !ppvVisibility
                    conMeFragQuickChat.isVisible = !ppvVisibility
                    conMeFragQuickChatHor.isVisible = ppvVisibility

                    GlideUtil.setImageView(entity.data.avatarUrl, imgViewMeFragHead)
                    txtMeFragNickName.text = entity.data.nickName+"· "+entity.data.age
                    txtMeFragNickName.visibility = View.VISIBLE
                    BaseConfig.getInstance.setString(SpName.userCode, entity.data.userCode)
                    txtMeFragVipTime.visibility = if (entity.data.isMember) View.VISIBLE else View.GONE
                    txtMeFragVipGetPremium.isVisible= !entity.data.isMember
                    if (entity.data.isMember) {
                        txtMeFragVipTime.text =
                            if (entity.data.autoRenew == 1) mActivity.getString(R.string.auto_subscription) else "Until: ${entity.data.expiryDate}"
                    }

                    if (CollectionUtils.isNotEmpty(entity.data.turnOnsList)) {
                        for (i in 0 until entity.data.turnOnsList.size) {
                            Glide.with(mActivity)
                                .load(entity.data.turnOnsList[i].imageUrl)
                                .diskCacheStrategy(DiskCacheStrategy.ALL)
                                .preload()
                        }
                    }

                    conMeFragSecretAlbum.setOnClickListener {
                        if (entity.data.privateAlbums != null && entity.data.isMember) {
                            IntentUtil.startActivity(PrivateAlbumActivity::class.java)
                        } else {
                            val intent = Intent(mActivity,BuyPrivateAlbumActivity::class.java)
                            intent.putExtra("isMember",entity.data.isMember)
                            mActivity.startActivityForResult(intent, PRIVATE_ALBUM_RESULT_CODE)
                        }
                    }

                    if (entity.data.isMember) {
                        getPrivate()
                    }
                    conMeFragQuickChatHor.setOnClickListener {
                        if (entity.data.isMember) {
                            FirebaseEventUtils.logEvent(FirebaseEventTag.Me_Flashchat_Buy.name)
                            MemberUnitaryBuy().openMemberUnitaryBuy(mActivity,2, callBackListener = {
                                if (it == BuyResultEnum.SUCCESS){
                                    getData()
                                    FirebaseEventUtils.logEvent(FirebaseEventTag.Me_Flashchat_Buysuccess.name)
                                }
                            })
                        } else {
                            FirebaseEventUtils.logEvent(FirebaseEventTag.Me_FC_Sub.name)
                            MemberBuy().openMemberBuy(mActivity,2,1, callBackListener = {
                                if (it == BuyResultEnum.SUCCESS){
                                    getData()
                                    FirebaseEventUtils.logEvent(FirebaseEventTag.Me_FC_Subsuccess.name)
                                }
                            })
                        }
                    }
                    conMeFragQuickChat.setOnClickListener {
                        if (entity.data.isMember) {
                            FirebaseEventUtils.logEvent(FirebaseEventTag.Me_Flashchat_Buy.name)
                            MemberUnitaryBuy().openMemberUnitaryBuy(mActivity,2, callBackListener = {
                                if (it == BuyResultEnum.SUCCESS){
                                    getData()
                                    FirebaseEventUtils.logEvent(FirebaseEventTag.Me_Flashchat_Buysuccess.name)
                                }
                            })
                        } else {
                            FirebaseEventUtils.logEvent(FirebaseEventTag.Me_FC_Sub.name)
                            MemberBuy().openMemberBuy(mActivity,2,1, callBackListener = {
                                if (it == BuyResultEnum.SUCCESS){
                                    getData()
                                    FirebaseEventUtils.logEvent(FirebaseEventTag.Me_FC_Subsuccess.name)
                                }
                            })
                        }
                    }
                    conMeFragSecretPic.setOnClickListener {
                        if (entity.data.isMember) {
                            FirebaseEventUtils.logEvent(FirebaseEventTag.Me_PP_Buy.name)
                            MemberUnitaryBuy().openMemberUnitaryBuy(mActivity,3, callBackListener = {
                                FirebaseEventUtils.logEvent(
                                    FirebaseEventTag.Me_PP_Buysuccess.name
                                )
                                getData()
                            })
                        } else {
                            FirebaseEventUtils.logEvent(FirebaseEventTag.Me_PP_Sub.name)
                            MemberBuy().openMemberBuy(mActivity,3,1, callBackListener = {
                                if (it == BuyResultEnum.SUCCESS){
                                    getData()
                                    FirebaseEventUtils.logEvent(FirebaseEventTag.Me_PP_Subsuccess.name)
                                }

                            })
                        }

                    }
                    conMeFragSecretVideo.setOnClickListener {
                        if (entity.data.isMember) {
                            FirebaseEventUtils.logEvent(FirebaseEventTag.Me_PV_Buy.name)
                            MemberUnitaryBuy().openMemberUnitaryBuy(mActivity,4, callBackListener = {
                                FirebaseEventUtils.logEvent(
                                    FirebaseEventTag.Me_PV_Buysuccess.name
                                )
                                getData()
                            })
                        } else {
                            FirebaseEventUtils.logEvent(FirebaseEventTag.Me_PV_Sub.name)
                            MemberBuy().openMemberBuy(mActivity,4,1, callBackListener = {
                                if (it == BuyResultEnum.SUCCESS){
                                    getData()
                                    FirebaseEventUtils.logEvent(FirebaseEventTag.Me_PV_Subsuccess.name)
                                }
                            })
                        }
                    }
                }
            })
            queryBenefits()


        }
    }

    fun getPrivate() {
        OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
            override fun addBody(requestBody: OkHttpBodyEntity) {
                requestBody.setPost(Constant.user_user_albums_url)
                requestBody.add("type", 3)
            }

        }, object : SDOkHttpResoutCallBack<PrivateAlbumEntity>(false) {
            override fun onSuccess(entity: PrivateAlbumEntity) {
                for (i in 0 until entity.data.images.size) {
                    Glide.with(mActivity)
                        .load(entity.data.images[i].imageUrl)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .preload()
                }
            }

        })
    }

    fun queryBenefits() {
        mView?.apply {
            OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                override fun addBody(requestBody: OkHttpBodyEntity) {
                    requestBody.setPost(Constant.user_member_query_benefits_url)
                }
            }, object : SDOkHttpResoutCallBack<QueryBenefitsEntity>(false) {
                override fun onSuccess(entity: QueryBenefitsEntity) {
                    if (entity.data != null) {
                        if (entity.data.size > 2) {
                            txtMeFragQuickChatHor.text = "x${entity.data[0].maxUses}"
                            txtMeFragQuickChat.text = "x${entity.data[0].maxUses}"
                            txtMeFragSecretPic.text = "x${entity.data[1].maxUses}"
                            txtMeFragSecretVideo.text = "x${entity.data[2].maxUses}"
                        }
                    }
                }
            })
        }

    }

    private fun addImage(selectList: ArrayList<LocalMedia>?) {
        mView?.apply {
            selectList?.forEach {
                if (it.mimeType.contains("mp4", true) || it.mimeType.contains(
                        "3gp",
                        true
                    ) || it.mimeType.contains("mov", true)
                ) {
                    if (it.duration > 60 * 1000) {
                        showToast(mActivity.getString(R.string.video_too_overlong_tip))
                        return
                    }
                    if (it.duration < 1000) {
                        showToast(mActivity.getString(R.string.video_too_short_tip))
                        return
                    }

                    if (it.size > 50 * 1024 * 1024) {
                        showToast(mActivity.getString(R.string.video_too_big_tip))
                        return
                    }
                }
                val path = when {
                    it.isCompressed -> {
                        it.compressPath
                    }

                    it.isCut -> {
                        it.cutPath
                    }

                    else -> {
                        it.realPath
                    }
                }
                LoadingDialog.showLoading(mActivity)
                if (path.contains(".mp4", true) || it.mimeType.contains(
                        ".3gp",
                        true
                    ) || it.mimeType.contains(".mov", true)
                ) {
                    if (it.duration > 60 * 1000) {
                        showToast(mActivity.getString(R.string.video_too_overlong_tip))
                        return
                    }
                    if (it.duration < 1000) {
                        showToast(mActivity.getString(R.string.video_too_short_tip))
                        return
                    }

                    if (it.size > 50 * 1024 * 1024) {
                        showToast(mActivity.getString(R.string.video_too_big_tip))
                        return
                    }
                    var suffix = "mp4"
                    if (it.mimeType.contains("/")) {
                        suffix = it.mimeType.substring(it.mimeType.lastIndexOf("/") + 1)
                    }
                    val compressPath =
                        KitStorageUtils.getImageSavePath(IMCenter.getInstance().context) +
                                File.separator + "${
                            Md5Util.MD5(
                                System.currentTimeMillis().toString()
                            )
                        }.$suffix"

                    VideoCompress.compressVideo(
                        IMCenter.getInstance().context,
                        path, compressPath, object : VideoCompress.CompressListener {
                            override fun onStart() {}
                            override fun onSuccess() {

                                val parse = Uri.parse("file://$compressPath")
                                val file = File(compressPath)
                                val length = file.length()
                                Log.e("~~~", "Compressing video file successes. $parse --- $length")
                                UploadPhoto.uploadFileNew(
                                    mActivity,
                                    compressPath,
                                    it.mimeType,
                                    object : UploadPhoto.OnLister {
                                        override fun onSuccess(
                                            successPath: String,
                                            imageCode: String
                                        ) {
                                            saveAlbums(successPath, it.duration)
                                        }

                                        override fun fail() {
                                            LoadingDialog.dismissLoading(mActivity)
                                            showToast("upload error,pls try again")
                                        }

                                    })
                            }

                            override fun onFail() {
                            }

                            override fun onProgress(percent: Float) {
                                Log.e("~~~", "The progress of compressing video file is $percent")
                            }
                        })
                } else {
                    UploadPhoto.uploadFileNew(
                        mActivity,
                        path,
                        it.mimeType,
                        object : UploadPhoto.OnLister {
                            override fun onSuccess(successPath: String, imageCode: String) {
                                saveAlbums(successPath, it.duration)
                            }

                            override fun fail() {
                                LoadingDialog.dismissLoading(mActivity)
                                showToast("upload error,pls try again")
                            }

                        })
                }
            }
        }
    }

    fun saveAlbums(image: String, videoLength: Long) {
        OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
            override fun addBody(requestBody: OkHttpBodyEntity) {
                requestBody.setPost(Constant.user_user_albums_add_url)
                requestBody.add("imageUrl", image)
                requestBody.add("type", 3)
                requestBody.add("videoLength", videoLength)

            }
        }, object : SDOkHttpResoutCallBack<PrivateAlbumAddEntity>() {
            override fun onSuccess(entity: PrivateAlbumAddEntity) {
                LoadingDialog.dismissLoading(mActivity)
                IntentUtil.startActivity(PrivateAlbumActivity::class.java)
                getData()
            }

            override fun onFailure(code: Int, msg: String) {
            }
        })
    }

    fun getMemberData() {
        mView?.apply {
            OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                override fun addBody(requestBody: OkHttpBodyEntity) {
                    requestBody.setPost(Constant.user_member_product_subscription_url)
                }

            }, object : SDOkHttpResoutCallBack<MemberSubscribeEntity>(false) {
                override fun onSuccess(entity: MemberSubscribeEntity) {
                    txtMeFragVipTitle.text = entity.data.memberDescription.tip
                    txtMeFragVipDesc.text = entity.data.memberDescription.content
                }

            })
        }

    }


    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> {
                    val selectList = PictureSelector.obtainSelectorList(data)
                    val intent = Intent(mActivity, PrivateAlbumViewActivity::class.java)
                    intent.putParcelableArrayListExtra(
                        PictureConfig.EXTRA_RESULT_SELECTION,
                        selectList
                    )
                    mActivity.startActivityForResult(intent, PictureConfig.CONFIRM_CHOOSE)
                }

                PictureConfig.CONFIRM_CHOOSE -> {
                    val bundle = Bundle()
                    val selectList = PictureSelector.obtainSelectorList(data)
                    bundle.putParcelableArrayList("selectList", selectList)
                    IntentUtil.startActivity(PrivateAlbumActivity::class.java, bundle)

//                    addImage(selectList)
                }
                PRIVATE_ALBUM_RESULT_CODE->{
                    getData()
                }
            }
        }
    }

}